<template>
    <div class="containerBox">
        <div class="tableTitle">
            <div class="tableIcon"><img src="@/assets/img/flower_brown.png" /></div>
            <div class="tableText">预约信息</div>
        </div>
        <div class="bgBox">
            <!-- qxz_redInput -->
            <div class="lines">
                <div class="couple" ref='phone'>
                    <label class="labels"><img class="required" src="@/assets/img/flower_red.png" alt=""> 手机号码</label>
                    <el-input 
                        size="small"
                        class="normal"
                        maxlength='20' 
                        :debounce="true" 
                        v-model="basicInfos.phone"
                        :disabled="pageType !== 'create'"
                        @input="lockInput"
                    />
                </div>
                <div class="checkPhone" @click="checkPhone" v-if="pageType === 'create'">验证手机号</div>
                <!-- <span class="tip" v-if="pageType === 'create' && !basicInfos.phone">&nbsp;&nbsp;&nbsp;请先输入手机号进行验证</span> -->
            </div>
            <div class="lines">
                <div class="couple" ref='source'>
                    <label class="labels"><img class="required" src="@/assets/img/flower_red.png" alt=""> 预约来源</label>
                    <div class="normal">CRM-手动创建</div>
                </div>
                <div class="couple" ref='source'>
                    <label class="labels"><img class="required" src="@/assets/img/flower_red.png" alt=""> 推广来源</label>
                    <div class="normal">{{getDep()}}</div>
                </div>
            </div>
            <div class="lines">
                <div class="couple">
                    <label class="labels"><img class="required" src="@/assets/img/flower_red.png" alt=""> 预约区域</label>
                    <el-cascader
                        size="small"
                        ref='area'
                        :disabled="isDisabled"
                        class="timeRange"
                        :options="optionsStore"
                        @change="changeArea"
                        @active-item-change="handleItemChangeStore"
                        :props="locateProp"
                        placeholder="请选择区域"
                        :value="orderArea"
                    >
                    </el-cascader>
                    <el-select 
                        class="timeRange" 
                        v-model="basicInfos.shop" 
                        placeholder="请选择门店" 
                        :disabled="isDisabled"
                        ref="shop"
                        size="small"
                    >
                        <el-option
                            v-for="item in storeList"  
                            :key="item.id"
                            :label="item.theNameOfTheStore"
                            :value="item.theNameOfTheStore"
                        />
                    </el-select>
                </div>
                <div class="couple" ref='name'>
                    <label class="labels"><img class="required" src="@/assets/img/flower_red.png" alt=""> 预约人</label>
                    <el-input size="small" class="normal" v-model="basicInfos.name" :disabled="isDisabled" />
                </div>
                <div class="couple">
                    <label class="labels" style="margin-right: 1rem;"><img class="required" src="@/assets/img/flower_red.png" alt=""> 性别</label>
                    <div class="normal" style="align-items: center;">
                        <el-radio v-model="basicInfos.sex" label="男" :disabled="isDisabled">男</el-radio>
                        <el-radio v-model="basicInfos.sex" label="女" :disabled="isDisabled">女</el-radio>
                    </div>
                </div>
            </div>
            <div class="lines">
                <div class="couple" ref='email'>
                    <label class="labels">邮箱</label>
                    <el-input size="small" class="normal" v-model="basicInfos.email" :disabled="isDisabled" />
                </div>
                <div class="couple" ref='contactAddress'>
                    <label class="labels">联系地址</label>
                    <el-cascader
                        size="small"
                        :disabled="isDisabled"
                        class="normal"
                        :options="optionsStore"
                        @active-item-change="handleItemChangeStore"
                        :props="locateProp"
                        @change="changeCity"
                        :value="contactAddress"
                    >
                    </el-cascader>
                </div>
                <div class="couple" ref='detailedAddress' style="justify-content: flex-end;width: 60rem;">
                    <label class="labels"> 详细地址</label>
                    <el-input size="small" class="normal" v-model="basicInfos.detailedAddress" placeholder="请输入详细地址" :disabled="isDisabled" />
                </div>
            </div>
            <div class="lines">
                <div class="couple">
                    <label class="labels"><img class="required" src="@/assets/img/flower_red.png" alt=""> 预约日期</label>
                    <el-date-picker
                        size="small"
                        ref='date'
                        :disabled="isDisabled"
                        class="normal"
                        formate="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        v-model="date"
                        type="date"
                        placeholder="选择日期"
                        :picker-options="expireTimeOption"
                    />
                </div>
                <div class="couple" ref='timeRange'>
                    <label class="labels"><img class="required" src="@/assets/img/flower_red.png" alt=""> 预约时间段</label>
                    <el-time-select
                        size="small"
                        ref='startTime'
                        :disabled="isDisabled"
                        class="timeRange"
                        placeholder="起始时间"
                        formate="HH:mm"
                        v-model="startTime"
                        :picker-options="{
                            start: '09:00',
                            step: '00:30',
                            end: '18:00',
                            maxTime: endTime
                        }"
                    >
                    </el-time-select>
                    <p style="transform: translateX(.5rem)">-</p>
                    <el-time-select
                        size="small"
                        ref='endTime'
                        :disabled="isDisabled"
                        class="timeRange"
                        formate="HH:mm"
                        placeholder="结束时间"
                        v-model="endTime"
                        :picker-options="{
                            start: '09:00',
                            step: '00:30',
                            end: '18:00',
                            minTime: startTime
                        }">
                    </el-time-select>
                </div>
                <div class="couple" ref='planBuyTime'>
                    <label class="labels">计划购买时间</label>
                    <el-select size="small" class="normal" v-model="basicInfos.planBuyTime" :disabled="isDisabled">
                        <el-option
                            v-for="item in planTimeArr"
                            :key="item.key"
                            :label="item.value" 
                            :value="item.key"
                        />
                    </el-select>
                </div>
            </div>
            <div class="lines">
                <div class="couple" ref='websiteSource'>
                    <label class="labels">网站来源</label>
                    <el-input size="small" class="normal" v-model="basicInfos.websiteSource" :disabled="isDisabled" />
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    import { getPlanTime, getResource, getProvince, getCity, getDistrict, getShop, checkPhone } from './axios'
    import { basicInfos, validateOptions, validateOptionsEx } from './datas.js'
    import { objDeepCopy, DRcookie } from '@/assets/js/common.js'
    import { Loading } from 'element-ui';
    export default {
        name: 'basicInfos',
        data() {
            return {
                // 编辑审核，记录之前的电话号
                previousData: '',
                // 禁用控制,新增时要先验证手机号
                isDisabled: true,
                // 计划购买时间选项
                planTimeArr: [],
                // 预约来源选项
                customerSource: [],
                // 预约地区
                area: '',
                // 预约门店选项
                storeList: [],
                // 日期。开始/结束时间
                date: '',
                startTime: '',
                endTime: '',
                // 联系地址连级选择
                options: [],
                // 预约地址连级选择
                optionsStore: [],
                // 默认选择的地址(联系地址)
                contactAddress: [],
                // 默认选择的地址(预约地址)
                orderArea: [],
                locateProp: {
                    value: 'value',
                    label: 'value',
                    children: 'cities'
                },
                basicInfos: Object.assign({}, basicInfos),
                timer: null,
                expireTimeOption: {
                    disabledDate(time) {
                        let date = new Date()
                        let times = date.getTime()
                        let hour = date.getHours()
                        let minute = date.getMinutes()
                        let second = date.getSeconds()
                        let dayTime = times - hour * 3600 * 1000 - minute * 60 * 1000 - second * 1000 - 1000
                        return time.getTime() <= dayTime;
                    }
                },
                // 有用户信息，禁用用户名，性别编辑
                hasInfo: false
            }
        },
        props: {
            origin: {
                type: String,
                required: true
            },
            pageType: {
                type: String,
                required: true
            }
        },
        methods: {
            lockInput() {
                this.isDisabled = true
            },
            // 表单验证
            validate() {
                if(this.isDisabled) {
                    this.$refs.phone.classList.add('qxz_redInput');
                    return false
                }
                let pass = true;
                // 关联到basicInfos对象里面的
                validateOptions.map(ele => {
                    let mixNode = this.$refs[ele._ref]
                    let node = this.isObj(mixNode) ? mixNode.$el : mixNode
                    let flag = this.basicInfos[ele.key] && !/^[ ]*$/.test(this.basicInfos[ele.key])
                    // 没填就不通过
                    !flag && (pass = false)
                    // 未通过的变成红色
                    flag
                    ?
                    (node.classList.remove('qxz_redInput'))
                    :
                    (node.classList.add('qxz_redInput'))
                })
                // 未关联在对象里面的
                validateOptionsEx.map(ele => {
                    let mixNode = this.$refs[ele._ref]
                    let node = this.isObj(mixNode) ? mixNode.$el : mixNode
                    let flag = this[ele.key] && !/^[ ]*$/.test(this[ele.key])
                    
                    // 没填就不通过
                    !flag && (pass = false)
                    // 未通过的变成红色
                    flag
                    ?
                    (node.classList.remove('qxz_redInput'))
                    :
                    (node.classList.add('qxz_redInput'))
                })
                let emailRegExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
                if(!/^[ ]*$/.test(this.basicInfos.email) && !emailRegExp.test(this.basicInfos.email) && this.basicInfos.email) {
                    this.$refs.email.classList.add('qxz_redInput')
                    pass = false
                }else {
                    this.$refs.email.classList.remove('qxz_redInput')
                }
                return pass
            },
            getDep() {
                let department = DRcookie.get('department')
                if(department) {
                    return `${department}`
                }else {
                    return ''
                }
            },
            // 关掉红框
            withdrawRedLattice() {
                validateOptions.map(ele => {
                    let mixNode = this.$refs[ele._ref]
                    let node = this.isObj(mixNode) ? mixNode.$el : mixNode
                    node.classList.remove('qxz_redInput')
                })
                validateOptionsEx.map(ele => {
                    let mixNode = this.$refs[ele._ref]
                    let node = this.isObj(mixNode) ? mixNode.$el : mixNode
                    node.classList.remove('qxz_redInput')
                })
                this.$refs.email.classList.remove('qxz_redInput')
            },
            isObj(target) {  
                return Object.prototype.toString.call(target) === "[object Object]"
            },
            getResult() {
                let pass = this.validate()
                if(!pass) {
                    return pass
                }
                let str1 = this.date.toString();
                let str2 = this.date.toString();
                this.basicInfos.reservationStartTime = `${this.date} ${this.startTime}:00`
                this.basicInfos.reservationEndTime = `${this.date} ${this.endTime}:00`
                
                this.storeList.forEach(ele => {
                    if(ele.theNameOfTheStore === this.basicInfos.shop) {
                        this.basicInfos.shopCode = ele.theFactory
                    }
                })
                return this.basicInfos
            },
            // 预约地址选择市
            changeArea(e) {
                let province = this.optionsStore.find(ele => ele.provinceName === e[0])
                let city = province.cities.find(ele => ele.cityName === e[1])
                let str = '';
                getShop(city.cityCode).then(res => {
                    if(res.data.status === 200) {
                        this.storeList = res.data.result
                        if(res.data.result.length === 0) {
                            this.basicInfos.shop = ''
                        }else{
                            let pass = false
                            res.data.result.map(ele => {
                                ele.theNameOfTheStore === this.basicInfos.shop && (pass = true)
                            })
                            !pass && (this.basicInfos.shop = '')
                        }
                    }
                })
                Array.isArray(e) && e.map((ele, index) => {
                    str += (index < e.length - 1 ? `${ele}-` : ele)
                })
                this.basicInfos.area = str;
            },
            // 预约地址省市选择
            handleItemChangeStore(item, reload) {
                let clue, index;
                this.optionsStore.map((ele, ind) => {
                    if(ele.provinceName === item[0]) {
                        clue = ele.provinceCode
                        index = ind
                    }
                })
                item.length === 1 && clue && getCity(clue).then(res => {
                    if(res.status === 200) {
                        let temp = res.data.result
                        temp.forEach(ele => {
                            ele.value = ele.cityName
                        })
                        this.optionsStore[index].cities = temp
                        reload && this.handleItemChangeStore(reload, 'getShop')
                    }
                }).catch(err => {
                    console.log('err: ', err)
                })
                if(item.length === 2) {
                    let indicator, cityCode, provinceCode = this.optionsStore[index].provinceCode;
                    this.optionsStore[index].cities.map((ele, ind) => {
                        if(ele.cityName === item[1]) {
                            cityCode = ele.cityCode;
                            indicator = ind
                        }
                    })
                    reload && this.changeArea(item)
                }
            },
            // 联系地址选择市
            changeCity(e) {
                let str = '';
                Array.isArray(e) && e.map((ele, index) => {
                    str += (index < e.length - 1 ? `${ele}-` : ele)
                })
                this.basicInfos.address = str;
            },
            // 校验电话号
            checkPhone() {
                if(this.timer) {
                    clearTimeout(this.timer);
                    this.timer = null
                }
                this.timer = setTimeout(() => {
                    let type;
                    // 新增时验证手机号
                    if(this.pageType !== 'create') {
                        return
                    }
                    this.origin === 'server' && (type = 1);
                    this.origin === 'shop' && (type = 2);
                    if(this.basicInfos.phone) {
                        spinner.text = '验证中...'
                        checkPhone(this.basicInfos.phone, type).then(res => {
                            if(res.data.status === 200) {
                                let infoType = res.data.result.infoType;
                                this.hasInfo = false
                                if(infoType === 1) {
                                    if(res.data.result.reservationInfo.type === 2) {
                                        this.$message({
                                            type: 'warning',
                                            message: '预约单已审核通过，无需再次创建'
                                        })
                                    }else if(res.data.result.reservationInfo.type === 1) {
                                        let loadingInstance = Loading.service({
                                            text: '已有未完成的预约单，正在跳转',
                                            background: 'rgba(0, 0, 0, 0.5)',
                                            fullscreen: true
                                        });
                                        setTimeout(() => {
                                            loadingInstance.close();
                                            this.$router.replace({name: 'verifyOrder', query: {pageType: 'verify', searchKey: res.data.result.reservationInfo.id}})
                                        }, 2000)
                                    }
                                }else if(infoType === 2) {
                                    this.isDisabled = false;
                                    let customerInfo = res.data.result.customerInfo
                                    customerInfo.email && (this.basicInfos.email = customerInfo.email)
                                    customerInfo.sex && (this.basicInfos.sex = customerInfo.sex)
                                    customerInfo.name && (this.basicInfos.name = customerInfo.name)
                                    this.hasInfo = true
                                    this.$emit('phone_check', false)
                                }else if(infoType === 3) {
                                    this.isDisabled = false;
                                    this.$emit('phone_check', false)
                                }
                            }else {
                                this.isDisabled = true;
                                this.$emit('phone_check', true)
                                this.$message({
                                    type: 'warning',
                                    message: '手机号格式不正确'
                                })
                            }
                        }).catch(err => {
                            console.log('err: ', err)
                        })
                    }else {
                        this.isDisabled = true;
                        this.$emit('phone_check', true)
                    }
                }, 300)
            },
            // 清空输入框
            clearInput() {
                this.basicInfos = Object.assign({}, basicInfos);
                this.date = '';
                this.startTime = '';
                this.endTime = '';
                this.contactAddress = [];
                this.orderArea = [];
            },
            // 编辑/审核填充内容
            dispatchData(data) {
                console.log(data, '快跑啊数据来了')
                this.previousData = data.phone;
                this.isDisabled = false;
                this.phone = data.phone;
                this.basicInfos = Object.assign(this.basicInfos, data);

                this.date = data.reservationStartTime.split(' ')[0]
                this.startTime  = data.reservationStartTime ? data.reservationStartTime.split(' ')[1].substr(0, 5) : ''
                this.endTime = data.reservationEndTime ? data.reservationEndTime.split(' ')[1].substr(0, 5) : ''

                let area = data.area ? data.area.split('-') : []
                this.orderArea = area
                area.length && this.handleItemChangeStore([area[0]], [area[0], area[1]])

                let contactAddress = data.address ? data.address.split('-') : []
                this.contactAddress = contactAddress
                contactAddress && this.handleItemChangeStore([contactAddress[0]])
            }
        },
        mounted() {
            // 计划购买时间
            getPlanTime().then(res => {
                if(res.status === 200) {
                    this.planTimeArr = res.data.result
                }
            }).catch(err => {
                console.log('err: ', err)
            });
            // 预约来源
            getResource().then(res => {
                if(res.status === 200) {
                    this.customerSource = res.data.result
                }
            }).catch(err => {
                console.log('err: ', err)
            })
            // 获取省
            getProvince().then(res => {
                if(res.status === 200) {
                    let temp = res.data.result;
                    let temper = objDeepCopy(temp)
                    temp.forEach(ele => {
                        if(ele.provinceName !== "北京" && ele.provinceName !== "天津" && ele.provinceName !== "重庆" && ele.provinceName !== "上海") {
                            ele.cities = []
                        }
                        ele.value = ele.provinceName
                    })
                    temper.forEach(ele => {
                        ele.value = ele.provinceName
                        ele.cities = []
                    })
                    this.options = objDeepCopy(temp)
                    this.optionsStore = objDeepCopy(temper)
                }
            }).catch(err => {
                console.log('err: ', err)
            })
        },
        // deactivated() {
        //     this.withdrawRedLattice()
        // }
    }
</script>
<style scoped>
    .containerBox{
        background: #FFF;
    }
    .bgBox{
        background: #FFF;
        padding: 0 2.4rem 0 0;
    }
    .tip{
        font-size: 1.4rem;
        color: red;
    }
    .couple{
        width: 30rem;
        display: flex;
        height: 4rem;
        font-size: 1.4rem;
        align-items: center;
        justify-content: center;
        color: #222222;
    }
    .lines{
        width: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
        flex-wrap: wrap;
        justify-content: flex-start;
    }
    .tableTitle{
        height: 4rem;
        display: flex;
        align-items: center;
        flex-direction: row;
        justify-content: flex-start;
        background: #FFF;
    }
    .tableIcon{
        width: .4rem;
        margin-left: 1rem;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .tableText{
        height: 100%;
        line-height: 4rem;
        margin-left: 0.4rem;
        font-size: 14px;
        font-weight: bold;
        color: #715D4A;
    }
    .timePicker{
        flex: 1;
        margin-left: 1rem;
    }
    .normal{
        flex: 1;
        display: flex;
        margin-left: 1rem;
    }
    .timeRange{
        flex: 1;
        display: flex;
        margin-left: 1rem;
    }
    .labels{
        width: 8rem;
        text-align: right;
    }
    .labels img{
        vertical-align: middle;
        margin-bottom: 2px;
    }
    .checkPhone{
        margin-left: 1rem;
        width: 8.5rem;
        height: 32px;
        text-align: center;
        line-height: 32px;
        color: #FFF;
        background: #715D4A;
        border-radius: .4rem;
        font-size: 1.4rem;
        cursor: pointer;
    }
</style>